'use strict';
const bcrypt = require('bcryptjs');
const { v4: uuidv4 } = require('uuid');

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    // 密码哈希
    const salt = await bcrypt.genSalt(10);
    const adminPassword = await bcrypt.hash('admin123', salt);
    const teacherPassword = await bcrypt.hash('teacher123', salt);
    const studentPassword = await bcrypt.hash('student123', salt);

    // 插入管理员用户
    const adminId = uuidv4();
    await queryInterface.bulkInsert('Users', [{
      id: adminId,
      username: 'admin',
      password: adminPassword,
      name: '系统管理员',
      email: 'admin@example.com',
      role: 'admin',
      isActive: true,
      createdAt: new Date(),
      updatedAt: new Date()
    }]);

    // 插入教师用户
    const teacherIds = [];
    const teacherData = [
      { name: '张教授', email: 'zhang@example.com' },
      { name: '李教授', email: 'li@example.com' },
      { name: '王教授', email: 'wang@example.com' }
    ];

    for (const teacher of teacherData) {
      const teacherId = uuidv4();
      teacherIds.push(teacherId);
      await queryInterface.bulkInsert('Users', [{
        id: teacherId,
        username: teacher.email.split('@')[0],
        password: teacherPassword,
        name: teacher.name,
        email: teacher.email,
        role: 'teacher',
        isActive: true,
        createdAt: new Date(),
        updatedAt: new Date()
      }]);
    }

    // 插入学生用户
    const studentIds = [];
    const studentData = [
      { name: '张三', email: 'zhangsan@example.com' },
      { name: '李四', email: 'lisi@example.com' },
      { name: '王五', email: 'wangwu@example.com' },
      { name: '赵六', email: 'zhaoliu@example.com' },
      { name: '钱七', email: 'qianqi@example.com' }
    ];

    for (const student of studentData) {
      const studentId = uuidv4();
      studentIds.push(studentId);
      await queryInterface.bulkInsert('Users', [{
        id: studentId,
        username: student.email.split('@')[0],
        password: studentPassword,
        name: student.name,
        email: student.email,
        role: 'student',
        isActive: true,
        createdAt: new Date(),
        updatedAt: new Date()
      }]);
    }

    // 插入课程数据
    const courseData = [
      {
        code: 'CS101',
        name: '计算机科学导论',
        description: '计算机科学基础入门课程',
        credit: 3,
        capacity: 50,
        location: '逸夫楼101',
        schedule: '周一 1-2节',
        status: 'published',
        teacherId: teacherIds[0],
        startDate: '2023-09-01',
        endDate: '2024-01-15',
        createdAt: new Date(),
        updatedAt: new Date()
      },
      {
        code: 'MATH201',
        name: '高等数学',
        description: '理工科基础数学课程',
        credit: 4,
        capacity: 100,
        location: '数学楼201',
        schedule: '周二 3-4节',
        status: 'published',
        teacherId: teacherIds[1],
        startDate: '2023-09-01',
        endDate: '2024-01-15',
        createdAt: new Date(),
        updatedAt: new Date()
      },
      {
        code: 'ENG101',
        name: '大学英语',
        description: '大学英语基础课程',
        credit: 2,
        capacity: 80,
        location: '外语楼101',
        schedule: '周三 5-6节',
        status: 'published',
        teacherId: teacherIds[2],
        startDate: '2023-09-01',
        endDate: '2024-01-15',
        createdAt: new Date(),
        updatedAt: new Date()
      },
      {
        code: 'PHYS101',
        name: '大学物理',
        description: '理工科基础物理课程',
        credit: 3,
        capacity: 60,
        location: '物理楼101',
        schedule: '周四 1-2节',
        status: 'published',
        teacherId: teacherIds[0],
        startDate: '2023-09-01',
        endDate: '2024-01-15',
        createdAt: new Date(),
        updatedAt: new Date()
      },
      {
        code: 'CHEM101',
        name: '大学化学',
        description: '理工科基础化学课程',
        credit: 3,
        capacity: 50,
        location: '化学楼101',
        schedule: '周五 3-4节',
        status: 'published',
        teacherId: teacherIds[1],
        startDate: '2023-09-01',
        endDate: '2024-01-15',
        createdAt: new Date(),
        updatedAt: new Date()
      }
    ];

    const courses = await queryInterface.bulkInsert('Courses', courseData, { returning: true });

    // 插入选课记录
    const enrollmentData = [];
    
    // 每个学生随机选3-5门课
    studentIds.forEach((studentId, index) => {
      const courseCount = Math.floor(Math.random() * 3) + 3; // 3-5门课
      const selectedCourses = [];
      
      while (selectedCourses.length < courseCount) {
        const randomCourse = Math.floor(Math.random() * courses.length);
        if (!selectedCourses.includes(randomCourse)) {
          selectedCourses.push(randomCourse);
          
          enrollmentData.push({
            studentId,
            courseId: courses[randomCourse].id,
            status: 'selected',
            enrolledAt: new Date(),
            createdAt: new Date(),
            updatedAt: new Date()
          });
          
          // 更新课程的当前选课人数
          queryInterface.sequelize.query(
            `UPDATE "Courses" SET "currentEnrollment" = "currentEnrollment" + 1 WHERE id = :courseId`,
            { replacements: { courseId: courses[randomCourse].id } }
          );
        }
      }
    });

    await queryInterface.bulkInsert('Enrollments', enrollmentData);
  },

  async down(queryInterface, Sequelize) {
    // 清空所有表数据
    await queryInterface.bulkDelete('Enrollments', null, {});
    await queryInterface.bulkDelete('Courses', null, {});
    await queryInterface.bulkDelete('Users', null, {});
  }
};
